package com.cn.boot.student.service.student.impl;

import com.cn.boot.student.entity.WordCollectRelationEntity;
import com.cn.boot.student.mapper.WordCollectMapper;
import com.cn.boot.student.service.common.impl.RedisServiceImpl;
import com.cn.boot.student.service.student.IWordCollectService;
import com.cn.boot.student.util.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

/**
 * 收藏逻辑层
 */
@Service
@CacheConfig(cacheNames = "word:collect")
public class WordCollectServiceImpl implements IWordCollectService {
    @Autowired
    private WordCollectMapper wordCollectMapper;
    @Autowired
    private RedisServiceImpl redisService;

    /**
     * 单词收藏
     *
     * @param wordCollectRelationEntity
     * @return
     */
    @Override
    public CommonResult collect(WordCollectRelationEntity wordCollectRelationEntity) {
        //得到前端传来的用户id和单词id，通过id查询关联表中是否存在数据
        Assert.notNull(wordCollectRelationEntity,"数据不能为空");
        List<WordCollectRelationEntity> list = wordCollectMapper.findAll(wordCollectRelationEntity);
        if(list.size() == 0){
            //当list==0时代表当前用户未收藏该单词，进行收藏更新数据
            Integer result = wordCollectMapper.add(wordCollectRelationEntity);
            if(result == 0){
                return CommonResult.failed("收藏失败!");
            }
            return CommonResult.success(result,"收藏成功！");
        }
        return CommonResult.failed("不能重复收藏！！！");
    }

    /**
     * 取消收藏
     *
     * @param wordCollectRelationEntity
     * @return
     */
    @Override
    public CommonResult delCollect(WordCollectRelationEntity wordCollectRelationEntity) {
        //得到前端传来的用户id和单词id，通过id查询关联表中是否存在数据
        Assert.notNull(wordCollectRelationEntity,"数据不能为空");
        Integer result = wordCollectMapper.del(wordCollectRelationEntity);
        if(result == 1){
            return CommonResult.success(result,"已取消收藏！！！");
        }
        return CommonResult.failed("取消失败！！！");
    }

    /***
     * 查询单词是否已被收藏
     * @param wordCollectRelationEntity
     * @return
     */
    @Override
    public CommonResult isCollected(WordCollectRelationEntity wordCollectRelationEntity) {
        Assert.notNull(wordCollectRelationEntity,"数据不能为空");
        List<WordCollectRelationEntity> list = wordCollectMapper.findAll(wordCollectRelationEntity);
        if(list.size() == 1){
            //返回已收藏标志
            return CommonResult.success("isHave");
        }
        //返回为收藏标志
        return CommonResult.success("noHave");
    }
}
